package org.jeecg.common.system.util;

import cn.hutool.json.JSONUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.ApiJwtVo;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @Author Scott
 * @Date 2018-07-12 14:23
 * @Desc JWT工具类
 **/
@Slf4j
public class ApiJwtUtil {

    public static final long EXPIRE_TIME = 5 * 24 * 60 * 60 * 1000;

    public static final String KEY = "ApiJwtVo";

    /**
     * 校验token是否正确
     *
     * @param token      密钥
     * @param apiJwtVo
     * @return 是否正确
     */
    public static boolean verify(String token, ApiJwtVo apiJwtVo) {
        try {
            String json = JSONUtil.toJsonStr(apiJwtVo);
            // 根据密码生成JWT效验器
            Algorithm algorithm = Algorithm.HMAC256(json);
            JWTVerifier verifier = JWT.require(algorithm).withClaim(KEY, json).build();
            // 效验TOKEN
            verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的用户名
     */
    public static ApiJwtVo getBusinessInfo(String token) {
        try {
            log.info("根据token获取用户信息，token:{}",token);
            DecodedJWT jwt = JWT.decode(token);
            String json = jwt.getClaim(KEY).asString();
            return JSONUtil.toBean(json,ApiJwtVo.class);
        } catch (JWTDecodeException e) {
            log.error("根据token获取信息异常",e);
            return null;
        }
    }

    /**
     * 生成签名,5day后过期
     *
     * @param apiJwtVo
     * @return 加密的token
     */
    public static String sign(ApiJwtVo apiJwtVo) {
        String json = JSONUtil.toJsonStr(apiJwtVo);
//        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(json);
        // 附带username信息
//        return JWT.create().withClaim(KEY, json).withExpiresAt(date).sign(algorithm);
        return JWT.create().withClaim(KEY, json).sign(algorithm);
    }

    /**
     * 根据request中的token获取用户账号
     *
     * @param request
     * @return
     * @throws JeecgBootException
     */
    public static ApiJwtVo getBusinessByToken(HttpServletRequest request) throws JeecgBootException {
        String accessToken = request.getHeader("X-Access-Token");
        ApiJwtVo vo = getBusinessInfo(accessToken);
        if (Objects.isNull(vo)) {
            throw new JeecgBootException("未获取到用户");
        }
        return vo;
    }


}
